
var sqlTextareaTip = '请输入SQL，仅支持Select语句';

//~~~~~~~~~~~~~~~~~~~~~grid~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

Ext.Loader.setConfig({
  enabled: true
});

Ext.require([
             'Ext.form.field.ComboBox',
             'Ext.form.FieldSet',
             'Ext.tip.QuickTipManager',
             'Ext.data.Model',
             'Ext.data.Store',
             'Ext.data.ArrayStore',
             'Ext.data.JsonReader',
             'Ext.data.Connection',
             'Ext.data.JsonStore',
             'Ext.window.MessageBox',
             'Ext.grid.*',
             'Ext.selection.CheckboxModel',
             'Ext.selection.CellModel'
         ]);
//~~~~~~~~~~~~~~~~~~~~~~~~数据库下拉菜单~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var databaseGroupCombo ;
var tableInfo;
var tableGroupCombo ;
var tableStore;
var tableName = "";

Ext.onReady(function() {
	
  if (!Ext.isChrome && Ext.util.Cookies.get("EasyCodeBroswerCheck") != "Y"){
	 Ext.MessageBox.alert('温馨提示', '内部应用，仅通过Chrome浏览器兼容性测试，建议你换成Chrome以免影响正常使用。');
	 Ext.util.Cookies.set("EasyCodeBroswerCheck","Y");
  }
	
  Ext.define("DatabaseGroup", {
      extend: "Ext.data.Model",
      fields: [
          { name: "id" },
          { name: "name" }
      ]
  });

  var store = Ext.create("Ext.data.Store", {
      model: "DatabaseGroup",
      proxy: {
          type: "ajax",
          url: "wiki/getDatabaseInfo.json",
          reader: new Ext.data.JsonReader({ model: "DatabaseGroup" })
      }
  });

  databaseGroupCombo = Ext.create('Ext.form.field.ComboBox', {
	    fieldLabel: '数据库',
	    renderTo: Ext.getBody(),
	    displayField: 'name',
	    width: 350,
	    labelWidth: 40,
	    store: store,
	    typeAhead: false,
	    editable:false,
	    padding:'0 0 0 5',
        name: 'DatabaseGroup',
        triggerAction: 'all',
        displayField: 'name',
        valueField: 'id',
        queryMode: 'remote',
        emptyText:'请选择'
	});
  
  databaseGroupCombo.on('change', function(field, newValue, oldValue, obj) {
	  
		  	   if (newValue == "" || newValue == undefined) {
		  		    return;
		  	   }
		  	   
		  	   tableInfo = [];
	   	       tableGroupCombo.store.loadData(tableInfo);
	   	       tableGroupCombo.setVisible(false);
	   	        
		       Ext.Ajax.request({
			   	    url: 'wiki/getTableInfo.json',
			   	    method:'post',
			   	    timeout : 60000,
			   	    params: {
			   	    	dbId : newValue
			   	    },
			   	    success: function(response){
			   	        var text = response.responseText;
			   	        var datas = Ext.decode(response.responseText);
			   	        tableInfo = datas;
			   	        tableGroupCombo.store.loadData(tableInfo);
			   	        tableGroupCombo.setVisible(true);
			   	    }
		       });
		       
		});   
  
});


//~~~~~~~~~~~~~~~~~~~~~~~~数据表下拉菜单~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Ext.onReady(function() {
	
tableInfo = [];
	
tableStore = Ext.create("Ext.data.ArrayStore", {
    autoDestroy: true,
    idIndex: 0,
    fields:[
            'name',
            {name:'id',type:'string'}
           ],
    data: tableInfo
});



tableGroupCombo = Ext.create('Ext.form.field.ComboBox', {
	    inputId:'tableGroupCombo',
	    fieldLabel: '数据表',
	    renderTo: Ext.getBody(),
	    displayField: 'name',
	    width: 300,
	    labelWidth: 40,
	    store: tableStore,
	    typeAhead: false,
	    editable:true,
	    padding:'0 0 0 5',
        name: 'TableGroup',
        triggerAction: 'all',
        displayField: 'name',
        valueField: 'id',
        queryMode: 'local',
        emptyText:'输入可补全。选中则立即查询该表',
        hidden:true,
        listeners:{
        	select:{
        		fn:function(combo,record,index) {
        			exeSql("SELECT * FROM " + Ext.get("tableGroupCombo").dom.value);
        		}
        	}
        }
	});
});

 

function getRangeByElement(obj) {
	var word = '';
	if (document.selection) {
		// IE
		obj.focus();
		selectobj = document.selection.createRange();
		if (selectobj.text.length > 0) {
			word = selectobj.text;
			document.selection.empty();
		}
	} else {
		p1 = obj.selectionStart;
		p2 = obj.selectionEnd;
		if (p1 || p1 == '0') {
			if (p1 != p2){
				word = obj.value.substring(p1, p2);
				obj.selectionStart=0;
				obj.selectionEnd=0;
			}
		}
	}
	return word;
}
 

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~viewport~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//wiki表格
var progrid;
//数据源
var sds;
//列模式
var columns;

var fieldsNames;

var fieldsType;

var jsonData;

var MyTable;

/**
 * 获取选中的行的数据的WIKI文本
 * @returns
 */
function getSelectedRowWiki()  
{  
    var record = progrid.getSelectionModel().getSelection();
    
    if(record == null || record.length == 0)
       return "";  
    
    var dataWiki = "";
    var moreThan;
    for(var i = 0; i < record.length; i++){
    	
    	var recordDetail = f_getMinRowRecord(record, moreThan);
    	moreThan = progrid.getStore().indexOf(recordDetail);
    	
    	var rowWiki = "|";
    	for (var j = 1; j < columns.length; j++) {
    		  var fieldName = columns[j].header;
    		  var fieldValue = recordDetail.get(fieldName);
    		  rowWiki = rowWiki + fieldValue + "|";
    	}
    	dataWiki = dataWiki + rowWiki + "\r\n";
    }
    return dataWiki;  
}  


Ext.onReady(function() {
	
	var sqlTextareaPanel = new Ext.form.Panel({
        frame: false,
        bodyPadding: 0,
        layout:'fit',
        collapsible: true,
        header:false,
        renderTo: Ext.getBody(),
        border :false,
        title: 'SQL输入框',
        items: [{
              html: '<textarea id=\"sqlTextarea\"  style=\"border:0;width:100%;height:100% !important;height:100;resize:none;\" class="sqlTextarea_blur" onfocus="f_sqlTextarea_focus(this);" onblur="f_sqlTextarea_blur(this);">' + sqlTextareaTip + '</textarea>',
              layout:'fit'
        }] 
    });
	
           var  vp =  Ext.create('Ext.Viewport', {
                 layout: {
                     type: 'border',
                     padding: 5
                 },
                 defaults: {
                     split: true
                 },
                 items: [{
                     region: 'north',
                     collapsible: false,
                     title: '',
                     split: true,
                     height: 35,
                     minHeight: 35,
                     bodyStyle:'background-color:#DDE7F4',
                     border:false,
                     html: '<span style=\"color:#03336F;\"><a href="' + f_getRootPath() + '" style="text-decoration: none" title="点击进入首页"><span style=\"font-weight:bold;font-size:25px;\">Auto Wiki</span> | <span style=\"font-size:13px;\">良无限单测Wiki生成工具</span></a> | <a href="' + f_getRootPath() + '" style="color:red;">更多工具点这里</a></span>'
                 },{
                     region: 'center',
                     layout: 'border',
                     border: true,
                     resizable:false,
                     title: '操作台',
                   	 dockedItems: [{
                         xtype: 'toolbar',
                         dock: 'top',
                         minHeight: 30,
                         items: [
							{
							    text: '运行SQL',
							    iconCls:'execute2-button',
							    handler: function(){
							    	exeSql("");
							    }
							},"-",databaseGroupCombo,"-",tableGroupCombo 
                         ]
                     }],
                     items: [
								{
								    region: 'north',
								    layout: 'fit',
								    border: false,
								    resizable:false,
								    collapsible: true,
				                    split: true,
				                    height: 100,
				                    minHeight: 100,
				                    header:false,
								    title: '',
								    items: [
											 sqlTextareaPanel
								            ]
								},{
								    region: 'center',
								    layout: 'fit',
								    border: true,
								    resizable:false,
								    collapsible: false,
				                    split: true,
				                    header:true,
				                    minHeight: 100,
				                    id:'r1',
								    title: 'Wiki生成区',
								    items: [
												{
												  title: '',
												  id: 'wikiGridId',
												  header:false,
												  html: '<div id=\"wikiGrid\"></div>'
												}
								           ]
								}
						    ]
                 }]
             });
         });
 


function exeSql(isql){
	var databaseId = databaseGroupCombo.getValue();
	if (databaseId == null) {
		 Ext.MessageBox.alert('提示信息', '请先选择你要使用的数据库。');
		 return;
	}
	
	var sql = "";
	if (isql == ""){
		  sql = getRangeByElement(document.getElementById("sqlTextarea"));
	} else {
		sql = isql;
	}
	
	if (sql == "") {
		sql = document.getElementById("sqlTextarea").value;
	}
	
	if (sql == "") {
		 Ext.MessageBox.alert('提示信息', '请输入SQL语句。');
		 return;
	}
	
    if (progrid != null) {
    	progrid.hide();
    }
    
    var myMask = new Ext.LoadMask(Ext.getBody(), {//也可以是Ext.getCmp('').getEl()窗口名称
    	msg    : "查询中，请稍候...",//你要写成Loading...也可以
    	msgCls : 'z-index:10000;',
    	removeMask : true// 完成后移除
    });
    myMask.show();
	var conn = new Ext.data.Connection();
	conn.request({
    	url:'wiki/executeSql.json?dbInfoId=' + databaseId + "&sql=" + sql,
    	
    	callback:function(options, success, response){
    		
	    	var json = Ext.decode(response.responseText);
	    	if (json.errorFlag) {
	    		tableName = "";
	    		myMask.hide();
	    		Ext.MessageBox.alert('出错啦！', json.message);
	        	return;
	    	}
	    	
	    	columns = json.columModle;
	    	fieldsNames = json.fieldsNames;
	    	fieldsType = json.fieldsType;
	    	jsonData = json.data;
	    	tableName = json.tableName;
	    	
	        MyTable = Ext.define('MyTable', {  
                extend : 'Ext.data.Model',  
                fields : fieldsNames,  
                idProperty : 'ID'// 极为重要的配置。关系到表格修改数据的获取  
            });  
	    	
	        sds = new Ext.data.JsonStore({
		    	data: json.data,
		    	fields:json.fieldsNames
	    	});
	    	
	        cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	    	    dbclicksToEdit: 1
	    	});
	        
	        if (progrid != null) {
	        	progrid.reconfigure(sds , columns);
	        	progrid.show();
	        	
		        if (progrid.getStore().getCount() != 0){
		        	Ext.getCmp('rMenu5').disable();
		        } else {
		        	Ext.getCmp('rMenu5').enable();
		        }
		        
	        	myMask.hide();
	        	return;
	        }
	        
	        //右键菜单
	        //创建右键菜单选项键
	        var rightMenu = new Ext.menu.Menu({
	                 id:'rightclickCount',
	                 items:[
						        {
							        id:'rMenu1',
							        text:'复制Wiki文本',
							        handler:function(){
							        	var insertWiki = "";
							        	if (tableName == "" || tableName == "null"){
							        		tableName = "请自填表名";
							        	}
							        	insertWiki = "|INSERT|" + tableName + "|";
							        	
							        	//表头的WIKI文本
							        	var headerWiki = "|";
							        	for (var i = 1; i < columns.length; i++) {
							        		headerWiki = headerWiki + columns[i].header + "|";
							        	}
							        	if(insertWiki != ""){
							        		headerWiki = insertWiki + "\r\n" + headerWiki;
							        	}
							        	
							        	var rowWiki = getSelectedRowWiki();
							        	var allWiki = headerWiki + "\r\n" + rowWiki;
							        	
							        	if (Ext.isIE){
							        		window.clipboardData.setData("Text", allWiki);
							        	} else {
										        $("#copyTextarea").text(allWiki);
										  	  var copyWin =  Ext.MessageBox.show({
										          title: '当前浏览器不支持自动复制',
										          msg: '请鼠标移进文本域，CTRL+C手动复制:<br/><br/><textarea  cols="60" rows="5" onmousemove="this.select();" id="copyTextarea" style="width:300px; word-wrap : normal; resize:none; ">' + allWiki + '</textarea>',
										          width:320,
										          buttons: Ext.MessageBox.OK,
										          buttonText:{
										               ok: "关闭" 
										          }
										      });
							        	}
							        	
							        }
						        },{
						        	id:'rMenu5',
							        text:'自动生成数据',
							        handler:function(){
							        	
							        	if (fieldsType == null || fieldsType == undefined){
							        		Ext.MessageBox.alert('温馨提示', '没有生成数据的目标表，请先查询表。');
							        		return;
							        	}
							        	
							        	var dataJson = "{";
								    	for (var i=0; i< fieldsType.length; i++){
								    		var ft = fieldsType[i];
								    		var ftArray = ft.split(",");
								    		
								    		var dataContent = "";
								    		if (ftArray[1] == "String"){
								    			dataContent = ftArray[0] + "#AUTO";
								    		} else if (ftArray[1] == "Date"){
								    			dataContent = "2013-01-01 12:00:00";
								    		} else if (ftArray[1] == "Long") {
								    			dataContent = "123456";
								    		} else if (ftArray[1] == "Integer"){
								    			dataContent = "123";
								    		}
								    		
								    		dataJson = dataJson + "" + ftArray[0] + ":'" + dataContent + "',";
								    	}
								    	
								    	dataJson = dataJson.substring(0, dataJson.length-1);
								    	dataJson = dataJson + "}";
								    	var autoDataJson = Ext.decode(dataJson);
								    	var　autoData　=　new　MyTable(autoDataJson);
								    	sds.insert(0, autoData);
								    	//不可用
								    	Ext.getCmp('rMenu5').disable();
							        }
						        },{
						        	id:'rMenu2',
							        text:'删除选中行',
							        handler:function(){
							        	var count = progrid.getStore().getCount();
							        	var record = progrid.getSelectionModel().getSelection();
							        	if(record.length==0){
							        		Ext.MessageBox.alert('温馨提示', '请先选中要删除的行。');
							        		return;
							        	} else if (record.length == count){
							        		Ext.MessageBox.alert('温馨提示', '不能清空数据，请至少保留一行数据。');
							        		return;
							        	} else {
							        		for (var i = 0; i < record.length; i++) {
							        			sds.remove(record[i]);
							        		}
							        	}
							        }
						        },{
						        	id:'rMenu3',
							        text:'仅保留选中行',
							        handler:function(){
							        	
							        	var record = progrid.getSelectionModel().getSelection();
							        	var count = progrid.getStore().getCount();
							        	if(record.length==0){
							        		Ext.MessageBox.alert('温馨提示', '请先选中要保留的行。');
							        		return;
							        	} else {
							        		
							        		var selArray = new Array();
							        		for (var j = 0; j < record.length; j++){
						        				var selId = record[j].id;
						        			    selArray.push(selId);
						        			}
							        		
							        		var pendingDelRow = new Array();
							        		for (var i = 0; i < count; i++){
							        			var rowData = sds.getAt(i);
							        			var rowId = rowData.id;
							        			var isSelected = false;
							        			for (var j = 0; j < selArray.length; j++){
							        				var selId = selArray[j];
							        				if (selId == rowId){
							        					isSelected = true;
							        				}
							        			}
							        			if (isSelected == false){
							        				pendingDelRow.push(rowData);
							        			}
							        		}

							        		for (var i = 0 ; i < pendingDelRow.length; i++){
							        			sds.remove(pendingDelRow[i]);
							        		}
							        		
							        	}
							        }
						        },{
						        	id:'rMenu4',
							        text:'复制并插入',
							        handler:function(){
							        	var count = progrid.getStore().getCount();
							        	var record = progrid.getSelectionModel().getSelection();
							        	if(record == null || record.length==0){
							        		Ext.MessageBox.alert('温馨提示', '请先选中要复制的行。');
							        		return;
							        	}
							        	//{name:'123',id:'1000'},{name:'123',id:'1000'}
							        	var lastSelectRowId = -1;
							        	for (var i = 0; i < record.length; i++){
							        		var thisSelectRowId = progrid.getStore().indexOf(record[i]) + 1;
							        		if (thisSelectRowId > lastSelectRowId){
							        			lastSelectRowId = thisSelectRowId;
							        		}
							        	}
							        	
							        	var moreThan;
							            for(var i = 0; i < record.length; i++){
							            	var recordDetail = f_getMinRowRecord(record,moreThan);
							            	moreThan = progrid.getStore().indexOf(recordDetail);
							            	var rowWiki = "{";
							            	for (var j = 1; j < columns.length; j++) {
							            		  var fieldName = columns[j].header;
							            		  var fieldValue = recordDetail.get(fieldName);
							            		  rowWiki = rowWiki + fieldName + ":'" + fieldValue + "',";
							            	}
							            	rowWiki = rowWiki.substring(0, rowWiki.length-1);
							            	rowWiki = rowWiki + "}";
							            	var dataJson = Ext.decode(rowWiki);
							            	var insertData　=　new　MyTable(dataJson);
							            	sds.insert(lastSelectRowId++, insertData);
							            	progrid.getView().refresh();
							            }
							            
							        }
						        }
					        ]
	         
	        });
	        

	        
	        var wikiGridHeight = Ext.get('wikiGridId').getHeight();
	        progrid = new Ext.grid.GridPanel({
		    	store:sds,
		    	columns:columns,
		    	columnLines: true,
		    	stateful: true,
		        collapsible: false,
		        multiSelect: true,
		        title: '',
		    	loadMask : true,
		    	renderTo: 'wikiGrid',
		    	header:false,
		    	multiSelect: true,
		    	autoScroll:true,
		        height:wikiGridHeight,
		        containerScroll : true,
		    	viewConfig : {
		            enableTextSelection: false
		    	},
		    	plugins: [cellEditing]
	    	});
	        
	        progrid.getEl().on('contextmenu', function(e, t) {
	            e.stopEvent();
	            rightMenu.showAt(e.getXY());
	        });
	        
	        if (progrid.getStore().getCount() != 0){
	        	Ext.getCmp('rMenu5').disable();
	        } else {
	        	Ext.getCmp('rMenu5').enable();
	        }
	        
	        myMask.hide();
    	}
	
	});
}

//获取最小的被选中的一行记录,并且要大于之前已经处理过的moreThan序号。
function f_getMinRowRecord(record, moreThan){
	var minSelectRowId = 100000;
	if (moreThan == undefined) moreThan = -1;
	var minRecord;
	for (var i = 0; i < record.length; i++){
		var thisSelectRowId = progrid.getStore().indexOf(record[i]);
		if (thisSelectRowId > moreThan && thisSelectRowId < minSelectRowId){
			minSelectRowId = thisSelectRowId;
			minRecord = record[i];
		}
	}
	return minRecord;
}

function f_sqlTextarea_blur(obj){
	if (obj.value == ''){
		obj.value = sqlTextareaTip;
		obj.className = 'sqlTextarea_blur';
	}
}

function f_sqlTextarea_focus(obj){
	if (obj.value == sqlTextareaTip){
		obj.value = '';
		obj.className = 'sqlTextarea_focus';
	}
}